package com.mingyuan.nacos;

import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.net.InetAddress;
import java.security.ProtectionDomain;

public class NacosJavassistTransformer implements ClassFileTransformer {


    public byte[] transform(ClassLoader loader,
                            String className,
                            Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain,
                            byte[] classfileBuffer) throws IllegalClassFormatException {

        // 判断当前处理的类是否需要进行Nacos注册
        if (shouldRegisterWithNacos(className)) {
            try {
                // 获取本地主机IP
                String ip = InetAddress.getLocalHost().getHostAddress();

                // 创建并初始化NamingService
                NamingService namingService = NamingFactory.createNamingService("150.158.78.193:8848");

                // 执行Nacos注册逻辑
                namingService.registerInstance("nacos-javassist-demo", ip, 8081);
                System.out.println(ip + " 已成功注册到Nacos！");

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return classfileBuffer; // 返回原始字节码数据或者修改后的字节码数据
    }

    private boolean shouldRegisterWithNacos(String className) {
        // 根据className判断是否应该进行Nacos注册，这里可以根据具体规则自行定义
        return className.contains("Nacos");
    }
}
